let App = {
	// 全局配置
	baseUrl: 'https://mh.mytshop.cn/index.php/api',
	// baseUrl: 'http://blindbox.jisapp.cn/index.php/api',
	/**
	 * post请求
	 */
	APIRequest(url, data,method = 'POST') {
		let token = uni.getStorageSync('token');
		let header = {};
		if (token == '') {
			header = {};
		} else {
			header = {
				'token': token
			};
		}
		return new Promise((resolve, reject) => {
			uni.request({
				url: App.baseUrl + url,
				header: header,
				method,
				data: data,
				success: (result) => {
					// console.log("result: ",result);
					if (result.statusCode === 200) {
						let { data } = result;
						if (data.code === 200) {
							resolve(data.data)
						} else if (data.code === 202) {
							uni.hideLoading();
							console.log(url,'url登录已过期');
							uni.showModal({
								title: '温馨提示',
								content: '登录已过期，请重新登录',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}
								}
							})
						} else {
							uni.hideLoading();
							App.showError(data.msg);
						}
					} else {
						uni.hideLoading();
						App.showError('请求错误，请重试');
						return reject()
					}
				}
			})
		})
	},
	//上传图片
	uploadImage(file) {
		let token = uni.getStorageSync('token');
		let requestUrl = App.baseUrl + '/index/upload';
		return new Promise((resolve, reject) => {
			uni.uploadFile({
				url: requestUrl,
				name: 'file',
				files:[{
					uri:file
				}],
				header: {
					'token': token
				},
				success: (uploadFileRes) => {
					console.log(uploadFileRes);
					if (uploadFileRes.statusCode === 200) {
						// 成功
						let imgData = JSON.parse(uploadFileRes.data)
						if (imgData.code === 200) {
							resolve(imgData)
						} else if (imgData.code === 202) {
							uni.showModal({
								title: '温馨提示',
								content: '登录已过期，请重新登录',
								showCancel: false,
								success: (res) => {
									if (res.confirm) {
										uni.removeStorageSync('token');
										uni.redirectTo({
											url: '/pages/login/login'
										})
									}
								}
							})
							uni.hideLoading();
						} else {
							uni.hideLoading();
							App.showError(imgData.msg);
						}
					} else {
						uni.hideLoading();
						App.showError('上传失败，请重新上传');
						return reject()
					}
				},
				fail(uploadFileRes) {
					console.log(uploadFileRes);
					uni.hideLoading();
					uni.showModal({
						title: "上传失败",
						content: JSON.parse(uploadFileRes.data).msg,
						showCancel: false
					});
					return rej()
				}
			});
		})
	},
	/**
	 * 对象转URL
	 */
	urlEncode(data) {
		var _result = [];
		for (var key in data) {
			var value = data[key];
			if (value.constructor == Array) {
				value.forEach(function(_value) {
					_result.push(key + "=" + _value);
				});
			} else {
				_result.push(key + '=' + value);
			}
		}
		return _result.join('&');
	},
	/**
	 * URL转对象
	 */
	urlToObj(str) {
		var obj = {};
		var arr1 = str.split("?");
		var arr2 = arr1[1].split("&");
		for (var i = 0; i < arr2.length; i++) {
			var res = arr2[i].split("=");
			obj[res[0]] = res[1];
		}
		return obj;
	},

	/**
	 * 显示成功提示框
	 */
	showSuccess(msg, callback) {
		uni.showToast({
			title: msg,
			icon: 'success',
			mask: true,
			duration: 1000,
			success() {
				callback && (setTimeout(function() {
					callback();
				}, 1000));
			}
		});
	},

	/**
	 * 显示失败提示框
	 */
	showError(msg, callback, showCancel = false) {
		uni.showModal({
			title: '温馨提示',
			content: msg,
			showCancel: showCancel,
			success(res) {
				callback && callback(res);
			}
		});
	},
	/**
	 * 获取当前经纬度
	 */
	getLocation() {
		let App = this;
		return new Promise((resolve, reject) => {
			uni.getLocation({
				type: "gcj02", // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
				success(res) {
					resolve(res);
				},
				fail(res) {
					resolve({
						latitude: "",
						longitude: ""
					});
				},
				complete(res) {
					console.log(res);
				}
			});
		})
	},
	/**
	 * 查看位置
	 */
	openLocation(options) {
		let App = this;
		if (!!options.location) {
			uni.openLocation({
				name: options.storename,
				address: options.address,
				latitude: Number(options.location.lat),
				longitude: Number(options.location.lng),
				success() {
					options.success && options.success();
				}
			});
		} else {
			App.showError("经纬度信息不完整,请确认后重试");
		}
	},
	/**
	 * 获取当前时间 格式:yyyy-MM-dd HH:MM:SS
	 */
	formatTime(date){
		const year = date.getFullYear()
		const month = date.getMonth() + 1
		const day = date.getDate()
		const hour = date.getHours()
		const minute = date.getMinutes()
		const second = date.getSeconds()
	
		return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
	},
	/**
	 * 补零
	 */
	formatNumber(n){
		n = n.toString()
		return n[1] ? n : '0' + n
	},
	/**
	 * 防抖
	 * @param {Function} fn 实际要执行的函数
	 * @param {Number} delay 延迟时间
	 * @return {Function} 返回一个去执行的函数
	 */
	debounce(fn, delay) {
		let timer = null;
		return function() {
			clearTimeout(timer); //清除定时器
			timer = setTimeout(() => {
				fn.apply(this, arguments);
			}, delay)
		}
	},
	/**
	 * 节流
	 * @param {Function} fn 实际要执行的函数
	 * @param {Number} delay 延迟时间
	 * @return {Function} 返回一个去执行的函数
	 */
	throttle(fn, delay) {
		//控制到底能不能进去，默认可以进去
		let ifRun = true;
		return function() {
			if (!ifRun) return //正在N秒内直接返回
			ifRun = false; //设置正在节流中
			setTimeout(() => {
				fn.apply(this, arguments);
				ifRun = true; //执行完就可以改变状态了
			}, delay)
		}
	}
}
export default {
	...App
}
